﻿
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>TableExport</title>
    <!--jquery-->
    <script src="https://cdn.bootcss.com/jquery/3.4.0/jquery.min.js"></script>
    <!--bootstrap-->
    <link href="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcss.com/popper.js/1.14.7/umd/popper.min.js"></script>
    <script src="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <!--fontawesome-->
    <script src="https://cdn.bootcss.com/font-awesome/5.8.1/js/all.min.js"></script>
    <!--bootstrap-table-->
    <link href="https://cdn.bootcss.com/bootstrap-table/1.14.2/bootstrap-table.min.css" rel="stylesheet">
    <script src="https://cdn.bootcss.com/bootstrap-table/1.14.2/bootstrap-table.min.js"></script>
    <!--bootstrap-table-lanuage-->
    <script src="https://cdn.bootcss.com/bootstrap-table/1.14.2/bootstrap-table-locale-all.min.js"></script>
    <!--bootstrap-table-export-->
    <script src="https://cdn.bootcss.com/bootstrap-table/1.14.2/extensions/export/bootstrap-table-export.min.js"></script>
    <!--在客户端保存生成的导出文件-->
    <script src="https://cdn.bootcss.com/FileSaver.js/2014-11-29/FileSaver.min.js"></script>
    <!--以XLSX（Excel 2007+ XML格式）格式导出表（SheetJS）-->
    <script src="https://cdn.bootcss.com/xlsx/0.14.2/xlsx.core.min.js"></script>
    <!--以PNG格式导出表格-->
    <!--对于IE支持包括 html2canvas 之前的 es6-promise-->
    <script src="https://cdn.bootcss.com/es6-promise/4.1.1/es6-promise.auto.min.js"></script>
    <script src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.min.js"></script>
    <!--将表导出为PDF文件-->
    <script src="https://unpkg.com/tableexport.jquery.plugin/libs/jsPDF/jspdf.min.js"></script>
    <script src="https://unpkg.com/tableexport.jquery.plugin/libs/jsPDF-AutoTable/jspdf.plugin.autotable.js"></script>
    <!--无论期望的格式如何，最后都包含 tableexport.jquery.plugin（不是tableexport）-->
    <script src="https://unpkg.com/tableexport.jquery.plugin/tableExport.min.js"></script>
</head>
<body>
    <!-- 模态框（Modal） -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="myModalLabel">用户信息</h4>
                </div>
                <div class="modal-body">
                    <table>
                        <tr>
                            <td>用户名</td>
                            <td><input type="text" id="username" value="" /></td>
                        </tr>
                        <tr>
                            <td>密码</td>
                            <td><input type="password" id="password" value="" /></td>
                        </tr>
                        <tr>
                            <td>生日</td>
                            <td><input type="date" id="birthday" value="" /></td>
                        </tr>
                        <tr>
                            <td>QQ</td>
                            <td><input type="text" id="qq" value="" /></td>
                        </tr>
                        <tr>
                            <td>邮箱</td>
                            <td>
                                <input type="text" id="email" value="" />
                                <input type="hidden" id="userid" value="" />
                            </td>
                        </tr>
                    </table>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" id="btnSave">提交更改</button>
                </div>
            </div> /.modal-content 
        </div> /.modal 
    </div>

    <div class="container">
        <button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">新增用户</button>
        <div id="toolbar">
            <select class="form-control">
                <option value="">Export Basic</option>
                <option value="all">Export All</option>
                <option value="selected">Export Selected</option>
            </select>
        </div>
        <button type="button" onclick="exportData()" class='btn btn-mini btn-info'>导出</button>
        <table id="table" data-locale="zh-CN">
            <tr>
                <th>fdf</th>
                <th>fdfsdf</th>

            </tr>
        </table>
        <!-- 分页查询 -->
        <div class="input-group justify-content-end" id="paginationDiv">
            <ul class="pagination pagination-sm" id="pagination">
            </ul>
            <!-- Query Result -->
            <span class="col-md-2" id="pageInfo"><label>共0条记录&nbsp;&nbsp;第1/1页</label></span>
            <span class="input-group col-md-2">
                <input type="text" id="pageInput" class="form-control text-center col-md-4" placeholder="1" />
                <span class="input-group-addon">
                    <button class="btn btn-outline-primary" onclick="queryDepts()">GO</button>
                </span>
            </span>
        </div>
    </div>
    <script>
        $(function () {
            $.ajax({
                url: "/api/Messages1",
                success: function (result) {
                    // 初始化表格
                    $('#toolbar').find('select').change(function () {
                        $('#table').bootstrapTable('destroy').bootstrapTable({
                            data: result,
                            pagination: true,//显示分页
                            clickToSelect: true,//单击列表选中
                            toolbar: "#toolbar",//显示工具栏
                            showToggle: true,//工具栏上显示列表模式切换
                            pagination: true,
                            striped: true,
                            sortable: true,                     //是否启用排序
                            sortOrder: "asc",                   //排序方式
                            sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
                            pageNumber: 1,                      //初始化加载第一页，默认第一页,并记录
                            pageSize: 1,                     //每页的记录行数（*）
                            pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
                            search: true,                      //是否显示表格搜索
                            strictSearch: false,
                            showColumns: true,                  //是否显示所有的列（选择显示的列）
                            showRefresh: true,                  //是否显示刷新按钮
                            minimumCountColumns: 2,             //最少允许的列数
                            clickToSelect: true,                //是否
                            showExport: true,//工具栏上显示导出按钮
                            clickToSelect: true,
                            exportDataType: $(this).val(),//显示导出范围
                            exportTypes: ['json', 'xml', 'png', 'csv', 'txt', 'sql', 'doc', 'excel', 'xlsx', 'pdf'],//导出格式
                            exportOptions: {//导出设置
                                fileName: 'Tablexxx',//下载文件名称
                            },
                            columns: [
                                {
                                    checkbox: true,
                                    visible: true                  //是否显示复选框
                                },
                                {
                                    field: 'fdf',
                                    checkbox: true,
                                    visible: $(this).val() === 'selected'
                                },
                                {
                                    field: 'ID',
                                    title: '编号'
                                },
                                {
                                    field: 'BookName',
                                    title: '需求书名'
                                }, {
                                    field: 'BookISBN',
                                    title: 'ISBN码'
                                },
                                {
                                    field: 'UserIdCard',
                                    title: '身份证号'
                                },
                                {
                                    field: 'Desc',
                                    title: '留言'
                                },

                                {
                                    field: '', title: '操作',
                                    formatter: operateFormatter(),
                                    width: 250
                                },
                            ]
                        })
                    }).trigger('change');
                }
            });
            function operateFormatter(value, row, index) {

                return [

                    '<button  style="width: 60px;height: 30px;" onclick="a(this);" type="button" class="btn btn-primary btn-xs">修改</button>&nbsp;', '<button  style="width: 60px;height: 30px;" onclick="b(this);" type="button" class="btn btn-primary btn-xs">获取时长</button>&nbsp;', '<button  style="width: 60px;height: 30px;" onclick="DelUser(this);" type="button" class="btn btn-primary btn-xs">删除</button>']
                    .join('');
            }
        })
        // 自定义按钮导出数据
        function exportData() {
            $('#table').tableExport({
                type: 'excel',
                exportDataType: "all",
                ignoreColumn: [0],//忽略某一列的索引
                fileName: 'Tablexxx',//下载文件名称
                onCellHtmlData: function (cell, row, col, data) {//处理导出内容,自定义某一行、某一列、某个单元格的内容
                    console.info(data);
                    return data;
                },

            });
        }



        /* 分页查询JS. */
        var pagination; //分页控件id
        var homePage = 1; //首页
        var lastPage = 0; //上一页(初始值为0)
        var firstPage = 1; //第一页(恒值1)
        var pageNo = 1; //页码(初始值为1)
        var nextPage = 0; //下一页(初始值为0)
        var endPage = 0; //末页(初始值为0)
        var pageSize = 20; //单页数量
        var pageCount = 1; //总页数(初始值为1)
        var totalCount = 0; //总数据量
        // currentPage=pageNo; //当前页数(暂未使用)
        // pageIndex=pageNo*pageSize; //起始页下标(放在后台计算)
        // pageGoInput //页面跳转输入框
        // pageGoBtn //页面跳转按钮

        $(function () {
            pagination = $("#pagination");
            initPagination(200);
        })

        function initPagination(total) {
            /*
             * 	totalCount = total == undefined ? 0 : total;
                if(totalCount == 0)
                {
                    //$('#pagination').hide();
                    return;
                }
             */

            /*
             * 分页初始化计算方式
             * homePage=1
             * lastPage==pageNo ? pageNo : pageNo-1
             * firstPage=1
             * nextPage==pageNo ? pageNo : pageNo+1
             * 如果firstPage=pageNo=endPage
             */
            pageCount = Math.ceil(totalCount / pageSize);
            pagination.html('');
            pagination.append("<li class='page-item' id='homePage' pageNo='1'><a class='page-link' href='#'>首页</a></li>");
            pagination.append("<li class='page-item' id='lastPage' pageNo='1'><a class='page-link' href='#'>上一页</a></li>");
            //page 1 is default active
            pagination.append("<li class='page-item active' id='firstPage' pageNo='1'><a class='page-link' href='#'>1</a></li>");
            if (pageCount > 1) {
                for (var i = 2; i <= pageCount; i++) {
                    pagination.append("<li class='page-item' pageNo='" + i + "'><a class='page-link' href='#'>" + i + "</a></li>");
                }
                pagination.append("<li class='page-item' id='nextPage' pageNo='" + (pageNo + 1) + "'><a class='page-link' href='#'>下一页</a></li>");
            } else {
                pagination.append("<li class='page-item disabled' id='nextPage' pageNo='1'><a class='page-link' href='#'>下一页</a></li>");
                //pageNo='1' 或者 pageNo='"+pageCount+"' 或者 pageNo='"+pageNo+"'
                //pagination.append("<li class='page-item disabled' id='nextPage' pageNo='"+pageNo+"'><a class='page-link' href='#'>下一页</a></li>");
            }
            endPage = pageCount;
            pagination.append("<li class='page-item' id='endPage' pageNo='" + pageCount + "'><a class='page-link' href='#'>末页</a></li>");
            //pageInfo
            $("#pageInfo").html("<label>共" + totalCount + "条记录&nbsp;&nbsp;第" + pageNo + "/" + pageCount + "页 </label>");

            //get pageNo
            $("#pagination li").click(function () {
                pageination($(this));
            });

            //get next page btn
            $("#nextPage").click(function () {
                nextPageClick($(this));
            });
        }

        function nextPageClick(page) {
            //	$("#pagination li").removeClass("active");
            // //遍历测试
            //	$("#pagination li[pageNo]").each(function(i){
            //		   var sortid=$(this).attr("pageNo");
            //		   console.log(sortid)
            //		});
        }

        function pageination(page) {
            //获取当前页数
            pageNo = Number(page.attr("pageNo"));
            lastPage = pageNo - 1;
            nextPage = pageNo + 1;
            lastPage = lastPage <= 1 ? 1 : lastPage;
            nextPage = nextPage >= pageCount ? pageCount : nextPage;
            var newLastPage = $("#lastPage").attr("pageNo", lastPage);
            var newNextPage = $("#nextPage").attr("pageNo", nextPage);
            //设置样式
            $("#pagination li").removeClass("active");
            //点击nextPage 则去掉上一页样式，设置新的pageNo样式为active
            if (page.attr("id") == "nextPage" || page.attr("id") == "lastPage") {
                //pageNo已是最新
                $("#pagination li[pageNo=" + pageNo + "]").addClass("active");

                //		//遍历测试
                //		$.each($("#pagination li[pageNo]"),function(i){
                //			if($(this).attr("pageNo")==nextPage)
                //			{
                //				alert($(this).attr("pageNo"))
                //				//console.log($(this).attr("pageNo"));
                //			}
                //		});
            }
            else {
                if (!page.hasClass("active")) {
                    page.addClass("active");
                }
            }
            alert("pageId=" + page.attr("id") + ", pageNo=" + pageNo + ", lastPage=" + lastPage + ", nextPage=" + nextPage)
            console.log("pageId=" + page.attr("id") + ", pageNo=" + pageNo + ", lastPage=" + lastPage + ", nextPage=" + nextPage)
        }





    </script>
    <script>
        $(function () {

            $("#btnSave").click(SaveUser);

        })
        function SaveUser() {

            if ($("#userid").val() == "")
                AddUser();
            else
                UpdateUser();



        }
        function DelUser() {
            var tr = $(this).parent().parent();
            var id = tr.children().get(1).innerHTML;
            $.ajax({
                url: "/api/Messages1?id=" + id,
                type: "Delete",
                success: function () {
                    $('#myModal').modal("hide");


                }


            })

        }
        function UpdateUser() {
            var user = {
                UserID: $("#userid").val(),
                UserName: $("#username").val(),
                UserPass: $("#password").val(),
                UserBirthday: $("#birthday").val(),
                UserQQ: $("#qq").val(),
                UserEmail: $("#email").val(),

            };
            $.ajax({
                url: "/api/userinfoes?id=" + $("#userid").val(),
                data: user,
                dataType: "json",
                type: "Put",
                success: function () {
                    $.getJSON("/api/UserInfoes", TianChongTable);
                    $('#myModal').modal("hide");
                    $("#username").val("");
                    $("#password").val("");
                    $("#birthday").val("");
                    $("#qq").val("");
                    $("#email").val("");
                    $("#userId").val("");

                }


            })
        }


        function AddUser() {
            var user = {
                UserName: $("#username").val(),
                UserPass: $("#password").val(),
                UserBirthday: $("#birthday").val(),
                UserQQ: $("#qq").val(),
                UserEmail: $("#email").val(),

            };
            $.post("/api/userinfoes", user, function () {
                $.getJSON("/api/UserInfoes", TianChongTable);
                $("#username").val("");
                $("#password").val("");
                $("#birthday").val("");
                $("#qq").val("");
                $("#email").val("");
                $("#userId").val("");
                $('#myModal').modal("hide");
            })
        }
        function EditUser() {
            var tr = $(this).parent().parent();
            $("#userid").val(tr.children().get(0).innerHTML);
            $("#username").val(tr.children().get(1).innerHTML);
            $("#password").val(tr.children().get(2).innerHTML);
            $("#birthday").val(tr.children().get(3).innerHTML);
            $("#qq").val(tr.children().get(4).innerHTML);
            $("#email").val(tr.children().get(5).innerHTML);
            $('#myModal').modal("show");

        }
        function TianChongTable(data) {
            $("#userTable").find("tr:gt(0)").remove();
            $.each(data, function (k, v) {
                var tr = $("<tr></tr>");
                tr.append("<td>" + v.UserID + "</td>");
                tr.append("<td>" + v.UserName + "</td>");
                tr.append("<td>" + v.UserPass + "</td>");
                tr.append("<td>" + v.Userbirthday + "</td>");
                tr.append("<td>" + v.UserQQ + "</td>");
                tr.append("<td>" + v.UserEmail + "</td>");
                tr.append("<td><button name='btnEdit'>编辑</button><button name='btnDel'>删除</button></td>");
                $("#userTable").append(tr);

            });
            $("button[name='btnEdit']").click(EditUser);
            $("button[name='btnDel']").click(DelUser);


        }
    </script>
</body>
</html>